#include "Cube.hh"

#include "common/stl.h"

Cube::Cube() :
    _vertex(0), _index(0), _colors(0), _shadertTst("tst")
{
    #ifdef DEBUG //  _shadertTst.init();
        if (!_shadertTst.init())
        {
            std::cerr << "shaders initialisation failure" << std::endl;
            return;
        }
    #else
        _shadertTst.init();
    #endif

    //{ tmp arrays
    float vertex[] = {-1, -1, -1,   1, -1, -1,   1, 1, -1,   -1, 1, -1,
                      -1, -1, 1,    1, -1, 1,    1, 1, 1,    -1, 1, 1};

    unsigned int index [] = {0, 1, 2,   2, 3, 0,    // Face 1
                             5, 1, 2,   2, 6, 5,    // Face 2
                             0, 1, 5,   5, 4, 0,    // Face 3
                             4, 5, 6,   6, 7, 4,    // Face 4
                             0, 4, 7,   7, 3, 0,    // Face 5
                             7, 6, 2,   2, 3, 7};   // Face 6

    float colors[] = {1,0,0,  0,1,0,  0,0,1,  1,1,1,
                      0,0,0,  1,1,0,  1,0,1,  1,1,0};
    //}end tmp arrays


    //{ dynamic arrays
    unsigned int const nbVertex(8 * 3);
    unsigned int const nbIndex(6 * 2 * 3); // 2 triangles
    unsigned int const nbColors(8 * 3);

    _vertex = new float[nbVertex];
    _index = new unsigned int[nbIndex];
    _colors = new float[nbColors];
    //} end dynamic arrays


    //{ dynamic arrays filling
    for (unsigned int i(0); i < nbVertex; ++i)
        _vertex[i] = vertex[i];

    for (unsigned int i(0); i < nbIndex; ++i)
        _index[i] = index[i];

    for (unsigned int i(0); i < nbColors; ++i)
        _colors[i] = colors[i];
    //} end dynamic arrays filling
}

Cube::~Cube()
{
    delete[] _vertex;
    delete[] _index;
    delete[] _colors;
}


void Cube::draw(Matrix &projection, Matrix &modelview)
{
    // modelview.stackPush();

    glUseProgram(_shadertTst.getProgramId());
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    GLuint shaderTstId = _shadertTst.getProgramId();
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, _vertex);
    glUniformMatrix4fv(glGetUniformLocation(shaderTstId, "projection"), 1, GL_TRUE, &projection[0][0]);
    glUniformMatrix4fv(glGetUniformLocation(shaderTstId, "modelview"), 1, GL_TRUE, &modelview[0][0]);

    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, _colors);

    for (int i(0); i < 6; i++)
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, &_index[i * 6]);

    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(0);

    // modelview.stackPop();
}
